import { constantRoutes } from '@/router'
import Layout from '@/layout/index'
import { getRouters, getAllRouters } from '@/api/menu'

function compare(property) {
  return function(a, b) {
    var value1 = a[property]
    var value2 = b[property]
    return value1 - value2
  }
}

const permission = {
  namespaced: true,
  state: {
    showBtnPer: [],
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: []
  },

  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      // state.routes = constantRoutes.concat(routes)
      state.routes = constantRoutes
    },
    SET_SHOWBTNPER: (state, showBtnPer) => {
      state.showBtnPer = showBtnPer
    },
    SET_DEFAULT_ROUTES: (state, routes) => {
      state.defaultRoutes = constantRoutes.concat(routes)
    },
    SET_TOPBAR_ROUTES: (state, routes) => {
      state.topbarRouters = state.routes
      // state.topbarRouters = routes.concat(index);
    },
    SET_SIDEBAR_ROUTERS: (state, routes) => {
      state.sidebarRouters = routes
    }
  },

  actions: {
    // 生成路由
    GenerateRoutes({ commit }) {
      return new Promise(resolve => {
        getRouters().then(roleMenu => {
          roleMenu.data.sort(compare('voOrder'))
          const resultArr = []; const btnPerList = []
          roleMenu.data.forEach(item => {
            if (item.children && item.moduleName !== 'merchant') {
              resultArr.push(item)
            }
            item.children.forEach(child => {
              child.children.forEach(element => {
                if (element.resType === 'F' && element.perms) {
                  btnPerList.push(element.perms)
                }
              })
            })
          })
          const sdata = JSON.parse(JSON.stringify(resultArr))
          const rdata = JSON.parse(JSON.stringify(resultArr))
          const sResultData = exchangeWords(sdata)
          const rResultData = exchangeWords(rdata)
          const sidebarRoutes = filterAsyncRouter(sResultData)
          const rewriteRoutes = filterAsyncRouter(rResultData, false, true)

          rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })
          commit('SET_ROUTES', rewriteRoutes)
          commit('SET_SIDEBAR_ROUTERS', constantRoutes.concat(sidebarRoutes))
          commit('SET_DEFAULT_ROUTES', sidebarRoutes)
          commit('SET_TOPBAR_ROUTES', sidebarRoutes)
          commit('SET_SHOWBTNPER', btnPerList)
          resolve(rewriteRoutes)
          // resolve([])
        })
      })
    }
  }

}

// 转换字段
function exchangeWords(asyncRouterMap, isChildren = false) {
  const routerArr = []
  // if (!isChildren) {
  //   routerArr.push(
  //     {
  //       path: '',
  //       component: Layout,
  //       redirect: 'index',
  //       alwaysShow: true,
  //       hidden: false,
  //       meta: {
  //         icon: '',
  //         title: '首页'
  //       },
  //       children: [
  //         {
  //           path: 'index',
  //           component: (resolve) => require(['@/views/index'], resolve),
  //           name: 'Index',
  //           meta: { title: '首页', icon: 'dashboard', affix: true }
  //         }
  //       ]
  //     }
  //   )
  // }
  asyncRouterMap.forEach(item => {
    if (item.children && item.children.length > 0) {
      item.children = exchangeWords(item.children, true)
    } else {
      delete item['children']
      delete item['redirect']
    }
    if (item.state) {
      if (isChildren) {
        routerArr.push({
          path: item.voPath,
          name: item.perms,
          component: item.voComponent,
          meta: {
            icon: item.voIcon,
            link: null,
            noCache: !!item.isChche,
            title: item.voName
          }
        })
      } else {
        if (item.perms === 'static') {
          routerArr.push(
            {
              path: '/static',
              component: 'Layout',
              redirect: 'index',
              children: [
                {
                  path: '',
                  component: 'static',
                  name: 'static',
                  meta: { title: '统计分析', icon: 'chart', affix: false }
                }
              ]
            }
          )
        } else {
          routerArr.push({
            path: item.voPath,
            name: item.perms,
            component: 'Layout',
            meta: {
              icon: item.voIcon,
              link: null,
              noCache: !!item.isChche,
              title: item.voName
            },
            hidden: !!item.deleted,
            isFrame: !!item.isFrame,
            children: item.children
          })
        }
      }
    }
  })
  return routerArr
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter(route => {
    if (type && route.children) {
      route.children = filterChildren(route.children)
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView' && !lastRouter) {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
    }
    children = children.concat(el)
  })
  return children
}

export const loadView = (view) => {
  if (process.env.NODE_ENV === 'development') {
    return (resolve) => require([`@/views/${view}`], resolve)
  } else {
    // 使用 import 实现生产环境的路由懒加载
    return () => import(`@/views/${view}`)
  }
}

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}


export default permission
